<template>
  <div class="app">
    <div class="header">
      <h1>🤖 AI 编程小助手</h1>
      <p>会话ID: {{ memoryId }}</p>
    </div>
    
    <div class="chat-container">
      <div class="messages" ref="messagesContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index" 
          :class="['message', message.role]">
          
          <div class="message-avatar">
            <span v-if="message.role === 'user'">👤</span>
            <span v-else>🤖</span>
          </div>
          
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
        
        <div v-if="isLoading" class="message ai">
          <div class="message-avatar">🤖</div>
          <div class="message-content">
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="input-area">
        <div class="input-container">
          <textarea 
            v-model="inputMessage" 
            placeholder="请输入您的编程问题或面试问题..."
            @keydown.enter.prevent="sendMessage"
            rows="3"
            ref="textareaRef">
          </textarea>
          <button @click="sendMessage" :disabled="!inputMessage.trim() || isLoading">
            {{ isLoading ? '发送中...' : '发送' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'

// 响应式数据
const memoryId = ref('')
const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref(null)
const textareaRef = ref(null)

// 生成随机会话ID（数字类型）
const generateMemoryId = () => {
  return Math.floor(Math.random() * 1000000) + 1
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return
  
  const userMessage = {
    role: 'user',
    content: inputMessage.value.trim(),
    timestamp: Date.now()
  }
  
  messages.value.push(userMessage)
  const currentMessage = inputMessage.value.trim()
  inputMessage.value = ''
  isLoading.value = true
  
  await scrollToBottom()
  
  try {
    // 使用SSE连接后端接口
    const eventSource = new EventSource(
      `http://localhost:8081/api/ai/chat?memoryId=${memoryId.value}&message=${encodeURIComponent(currentMessage)}`
    )
    
    let aiResponse = ''
    
    eventSource.onmessage = (event) => {
      if (event.data) {
        aiResponse += event.data
        
        // 更新或创建AI消息
        const existingAiMessage = messages.value.find(msg => 
          msg.role === 'ai' && msg.isStreaming
        )
        
        if (existingAiMessage) {
          existingAiMessage.content = aiResponse
        } else {
          messages.value.push({
            role: 'ai',
            content: aiResponse,
            timestamp: Date.now(),
            isStreaming: true
          })
        }
        
        scrollToBottom()
      }
    }
    
    eventSource.onerror = (error) => {
      console.error('SSE连接错误:', error)
      eventSource.close()
      
      // 如果AI消息不存在，创建错误消息
      if (!messages.value.some(msg => msg.role === 'ai' && msg.isStreaming)) {
        messages.value.push({
          role: 'ai',
          content: '抱歉，连接出现错误，请稍后重试。',
          timestamp: Date.now()
        })
      }
      
      isLoading.value = false
      scrollToBottom()
    }
    
    // 监听流结束
    setTimeout(() => {
      eventSource.close()
      
      // 标记流结束
      const aiMessage = messages.value.find(msg => 
        msg.role === 'ai' && msg.isStreaming
      )
      if (aiMessage) {
        aiMessage.isStreaming = false
      }
      
      isLoading.value = false
    }, 30000) // 30秒超时
    
  } catch (error) {
    console.error('发送消息错误:', error)
    messages.value.push({
      role: 'ai',
      content: '抱歉，发送消息时出现错误，请检查网络连接。',
      timestamp: Date.now()
    })
    isLoading.value = false
    scrollToBottom()
  }
}

// 初始化
onMounted(() => {
  memoryId.value = generateMemoryId()
  
  // 添加欢迎消息
  messages.value.push({
    role: 'ai',
    content: '您好！我是AI编程小助手，可以帮您解答编程学习、面试准备等相关问题。请问有什么可以帮助您的吗？',
    timestamp: Date.now()
  })
  
  // 自动聚焦输入框
  if (textareaRef.value) {
    textareaRef.value.focus()
  }
})
</script>

<style scoped>
.app {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  padding: 1rem 2rem;
  color: white;
  text-align: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.header h1 {
  font-size: 1.8rem;
  margin-bottom: 0.5rem;
  font-weight: 600;
}

.header p {
  font-size: 0.9rem;
  opacity: 0.8;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: 0 1rem;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem 0;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message {
  display: flex;
  gap: 0.75rem;
  max-width: 80%;
  animation: fadeIn 0.3s ease-in;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.message.ai {
  align-self: flex-start;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  flex-shrink: 0;
}

.message.user .message-avatar {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.message.ai .message-avatar {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
}

.message-content {
  flex: 1;
  min-width: 0;
}

.message-text {
  background: rgba(255, 255, 255, 0.9);
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  line-height: 1.5;
  word-wrap: break-word;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.message.user .message-text {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  border-bottom-right-radius: 0.25rem;
}

.message.ai .message-text {
  background: white;
  color: #333;
  border-bottom-left-radius: 0.25rem;
}

.message-time {
  font-size: 0.75rem;
  color: rgba(255, 255, 255, 0.7);
  margin-top: 0.25rem;
  text-align: right;
}

.message.ai .message-time {
  color: rgba(0, 0, 0, 0.5);
  text-align: left;
}

.input-area {
  padding: 1rem 0 2rem;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(255, 255, 255, 0.2);
}

.input-container {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  gap: 1rem;
  align-items: flex-end;
}

.input-container textarea {
  flex: 1;
  padding: 0.75rem 1rem;
  border: none;
  border-radius: 1rem;
  background: rgba(255, 255, 255, 0.9);
  resize: none;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5;
  outline: none;
  transition: all 0.3s ease;
}

.input-container textarea:focus {
  background: white;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.5);
}

.input-container button {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 1rem;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 80px;
}

.input-container button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.4);
}

.input-container button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 0.75rem 1rem;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) { animation-delay: -0.32s; }
.typing-indicator span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 滚动条样式 */
.messages::-webkit-scrollbar {
  width: 6px;
}

.messages::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 3px;
}

.messages::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header {
    padding: 1rem;
  }
  
  .header h1 {
    font-size: 1.5rem;
  }
  
  .message {
    max-width: 90%;
  }
  
  .input-container {
    flex-direction: column;
    gap: 0.75rem;
  }
  
  .input-container button {
    align-self: flex-end;
  }
}
</style>